<template>
  <div>
    <Category class="card-list" :disabled="scene === 1" />
    <el-card class="card-list">
      <div v-show="scene === 0">
        <el-button
          type="primary"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttr"
          >添加</el-button
        >
        <el-table :data="tableData" :border="true">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="attrName" label="名称" width="120" />
          <el-table-column label="值">
            <template #default="{ row }">
              <el-tag
                v-for="item in row.attrValueList"
                :key="item.id"
                class="tag-item"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>

              <el-popconfirm
                :title="`确认删除${row.attrName}`"
                width="200px"
                @confirm="deleteAttr(row)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene === 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input v-model="attrParams.attrName" />
          </el-form-item>
        </el-form>
        <el-button
          :disabled="!attrParams.attrName"
          type="primary"
          icon="Plus"
          @click="addAttrValue"
          >添加属性</el-button
        >
        <el-button type="primary" @click="cancel">取消属性</el-button>
        <el-table :border="true" :data="attrParams.attrValueList">
          <el-table-column
            type="index"
            width="80px"
            label="序号"
            align="center"
          ></el-table-column>
          <el-table-column label="属性名称">
            <template #default="{ row, $index }">
              <el-input
                v-if="row.flag"
                :ref="(element: InputInstance) => (inputArr[$index] = element)"
                v-model="row.valueName"
                @blur="blur(row, $index)"
              />
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值">
            <template #default="{ $index }">
              <el-button
                type="primary"
                @click="attrParams.attrValueList.splice($index, 1)"
                icon="Delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disable="!attrParams.attrValueList.length"
          >保存</el-button
        >
        <el-button type="primary" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { InputInstance } from 'element-plus'

import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import {
  reqAttr,
  reqAddorUpdateAttr,
  reqRemoveAttr
} from '@/api/product/attr/index'
import type {
  AttrResponseData,
  AttrList,
  Attr,
  AttrValue
} from '@/api/product/attr/type'
import useCategoryStore from '@/store/modules/category'
const categoryStore = useCategoryStore()

const tableData = ref<AttrList>([])
watch(
  () => categoryStore.c3Id,
  (c3Id) => {
    tableData.value = []

    if (!c3Id) return
    getAttr()
  }
)

const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  tableData.value = result.data
}
const scene = ref<number>(0)
const addAttr = () => {
  scene.value = 1
  Object.assign(attrParams, {
    attrName: '', //属性名
    attrValueList: [],
    categoryId: '', // 三级分类id
    categoryLevel: 3 // 代表是三级
  })
  attrParams.categoryId = categoryStore.c3Id
}
const updateAttr = (row: Attr) => {
  scene.value = 1

  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
const deleteAttr = async (row: Attr) => {
  await reqRemoveAttr(row.id as number)
  ElMessage({
    type: 'success',
    message: '删除成功'
  })
  getAttr()
}

const cancel = () => {
  scene.value = 0
}
const attrParams = reactive<Attr>({
  attrName: '', //属性名
  attrValueList: [],
  categoryId: '', // 三级分类id
  categoryLevel: 3 // 代表是三级
})

const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true
  })

  nextTick(() => {
    inputArr.value[inputArr.value.length - 1]?.focus()
  })
}
const save = async () => {
  await reqAddorUpdateAttr(attrParams)
  scene.value = 0
  ElMessage({
    type: 'success',
    message: attrParams.id ? '修改成功' : '添加成功'
  })
  getAttr()
}

const blur = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() === '') {
    attrParams.attrValueList.splice($index, 1)
    return
  }

  const repeat = attrParams.attrValueList.find(
    (item) => item !== row && item.valueName === row.valueName
  )
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '名称重复'
    })
    return
  }

  row.flag = false
}
const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[$index]?.focus()
  })
}
const inputArr = ref<InputInstance[]>([])

onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped lang="scss">
.card-list {
  & + .card-list {
    margin: 10px 0;
  }
}
.tag-item {
  margin: 5px;
}
</style>
